<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\model\ClientAccountModel;
use app\model\CrontabTaskModel;
use app\service\cdc\cost\TaskAccountService;
use app\service\CrontabTaskService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class MediaMaterialListWork extends BaseWork implements DailyStatWork
{
    public ?string $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('media_material_list_work');
        // 设置参数
        $this->setDescription('生成拉取任务队列')
            ->addArgument('task_type', Argument::REQUIRED, '任务类型  1：账户 2：视频  3：图片')
            ->addArgument('media_id', Argument::OPTIONAL, '媒体id')
            ->setHelp('php think media_material_list_work [task_type] [media_id]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $mediaId = intval($input->getArgument('media_id'));
        $taskType = intval($input->getArgument('task_type'));

        $this->setTag($mediaId . '-' . $taskType);
        $output->writeln('=======cost拉取素材脚本开始' . date('Y-m-d H:i:s', time()) . '=======');
        // 获取所有有效账户
        try {
            $redis = Cache::store('redis')->handler();
            $redisKey = TaskAccountService::getMaterialRedisKey($taskType, $mediaId);
            if ($redis->llen($redisKey) > 2000) {
                $output->writeln('队列已经存在，不再生成' . date('Y-m-d H:i:s', time()) . '=======');
                return;
            }

            $list = (new ClientAccountModel())->where('auth_valid', ClientAccountModel::STATUS_ENABLE)->where('media_id', $mediaId)->order('cost_sort', 'desc')->field(true)->select()->toArray();

            if (! $list) {
                $output->writeln('=======生成拉取任务队列结束' . date('Y-m-d H:i:s', time()) . '=======没有有效账户');
                return;
            }

            foreach ($list as $v) {
                // 存入redis队列
                $res = $redis->Rpush($redisKey, $v['id']);
                if (! $res) {
                    $output->writeln('插入队列失败，account_id:' . $v['id'] . ',' . date('Y-m-d H:i:s', time()) . '=======');
                }
            }
        } catch (\Exception $e) {
            $output->writeln($e->getMessage() . date('Y-m-d H:i:s', time()));
        }


        CrontabTaskService::setSingleTask($this);
        $output->writeln('=======拉取素材脚本结束' . date('Y-m-d H:i:s', time()) . '=======');
    }
}
